const mongoose = require("mongoose");
const GroupList = require("../models/grouplist");
const Project = require("../models/project");
const router = require("koa-router")();

router.get("/getlist", async (ctx) => {
  try {
    let author = ctx.state.user._id || "";
    const glist = await GroupList.find({ author });
    let data = await Promise.all(
      glist.map(async (item) => {
        const gid = mongoose.mongo.ObjectId(item._id);
        const count = await Project.find({
          groupID: gid,
          isDelete: false,
          isTemplate: false,
        }).countDocuments();
        const mapunit = {
          count,
          ...item._doc,
        };
        return mapunit;
      })
    );
    ctx.body = data;
  } catch (e) {
    ctx.status = 500;
    ctx.body = "服务器错误" + e.message;
  }
});

router.post("/addgroup", async (ctx) => {
  let author = ctx.state.user._id || "";
  const name = ctx.request.body.groupinput;
  author = mongoose.mongo.ObjectId(author);
  const state = await GroupList.create({
    name,
    author,
    _id: mongoose.mongo.ObjectId(),
  });
  ctx.body = state;
});

router.post("/setgroup", async (ctx) => {
  const _id = mongoose.mongo.ObjectId(ctx.request.body.gid);
  const name = ctx.request.body.name;
  console.log(_id, name);
  try {
    const state = await GroupList.updateOne(
      { _id: _id },
      { $set: { name } },
      {
        runValidators: true,
      }
    );
    ctx.body = {
      msg: state,
    };
  } catch (e) {
    console.log(e);
    ctx.body = {
      msg: "更新失败",
    };
  }
});

router.post("/deletegroup", async (ctx) => {
  try {
    const _id = ctx.request.body.gid;
    console.log(_id);
    const update = await Project.updateMany(
      { groupID: _id },
      { $set: { groupID: "-1" } },
      {
        runValidators: true,
        multi: true,
      }
    );
    console.log(update);
    const state = await GroupList.deleteOne({ _id });
    ctx.body = {
      msg: "删除成功",
      body: {
        update: update,
        state: state,
      },
    };
  } catch (e) {
    console.log(e);
    ctx.body = {
      msg: "删除失败",
    };
  }
});

module.exports = router;
